﻿/***************************
* 1.节庆活动列表
* 2.节庆活动详情
****************************/

/* 变量 */
var activity = "activity/generalActivity.html";
var activityDetail = "activity/generalActivityDetail.html";
var generalActivityRegister = "activity/generalActivityRegister.html";

/* 节庆活动 */
var contactsCallback_generalactivity = myApp.onPageInit('generalactivity', function (page) {

    //非微信浏览器下  不显示标题
    if (!ISS.utils.isWeiXin()) {
        mainView.hideNavbar();
        $$('.page-content').attr('style', 'margin-top:-44px')
    }
    //获取页面参数
    var userID = ISS.utils.getParameter("userID");
    if (userID && userID != undefined && userID != null && userID != "") {
        iss_localStorage.set("yuqing_appUserId", userID);
        mainView.hideNavbar();
        $$('.page-content').css('style', 'margin-top:-44px')
    }

    // 过滤
    $$(".navbar-inner .right img").hide();

    //删除滚动后重新添加滚动
    var flag_InfiniteScroll = true;
    //是否需要滚动加载
    var flag_needScroll = true;
    //滚动事件只执行一次
    var flag_execute = false;

    var index_tab1 = 1;
    var current_tabindex = 0;
    var size = 10;

    LoadActivityAll(index_tab1, size);
    //加载数据
    function LoadActivityAll(pageindex, pagesize) {
        var Account = ISS.utils.getParameter("Account");
        var conditionParams = {
            type: 1,
            serviceName: ISS_Constants.PortalServiceName.GetCatalogContentList,
            content: JSON.stringify({ 
                format: "json",
                Identifier: "wechat/activity",
            }),
        };
        $$.ajax({
            url: ISS_Constants.Url.const_portal_url,
            data: conditionParams,
            dataType: 'jsonp',
            jsonp: 'callback',
            success: function (data, status) {
                data = JSON.parse(data);

                if (data && data.results && data.results.length > 0) {
                    for (var i = 0; i < data.results.length; i++) {
                        if (data.results[i].F_SmallImage == undefined ||
                            data.results[i].F_SmallImage == null || data.results[i].F_SmallImage == "") {
                            data.results[i].F_SmallImage = NoPicture();
                        };
                        data.results[i].BeginDate = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.results[i].BeginDate)));
                        data.results[i].Account = Account;
                        //data.results[i].Distance = ISS.utils.toFixed(data.results[i].Distance, 2);
                    };

                    if (current_tabindex == 0) {
                        var searchTemplate = $$('#template-generalactivity-tab1').html();
                        if (searchTemplate) {
                            var compiledTemplate = Template7.compile(searchTemplate);
                            var html = compiledTemplate(data);
                            $$("#generalactivity_page #sub_stay_tab1 .content-block ul").append(html);
                            flag_InfiniteScroll = flag_needScroll = true;
                        }
                    }
                    //tab1综合,无限滚动只加载一次
                    if (!flag_execute) {
                        //只执行一次
                        flag_execute = true;
                        // 加载flag
                        var loading = false;
                        $$('.infinite-scroll').on('infinite', function () {
                            //综合 价格 距离 切换
                            if (!flag_needScroll) {
                                flag_needScroll = true;
                                return;
                            }
                            //查询时,删除滚动后重新绑定pageindex
                            if (!flag_InfiniteScroll) {
                                flag_InfiniteScroll = true;
                                return;
                            }
                        });
                    }
                    if (current_tabindex == 0 && $$("#activity_page #sub_stay_tab1 .content-block ul li").length >= data.total) {
                        // 删除加载提示符
                        $$('.infinite-scroll-preloader1').remove();
                        // 加载完毕，则注销无限加载事件，以防不必要的加载
                        myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    }

                }
                else {
                    // 删除加载提示符
                    myApp.detachInfiniteScroll($$('.infinite-scroll'));
                    if (current_tabindex == 0) {
                        $$('.infinite-scroll-preloader1').remove();
                        if (pageindex == 1)
                            $$("#activity_page #sub_stay_tab1 .content-block").append("<div id='noAnswer' style='margin:auto;text-align:center'>对不起，您搜索的结果不存在！</div>");
                    }
                }
            },
            error: function (xhr, status) { }
        });
    }
});

var contactsCallback_generalactivityDetail = myApp.onPageInit('generalactivityDetail', function (page) {
    //非微信浏览器下  不显示标题
    if (!ISS.utils.isWeiXin()) {
        mainView.hideNavbar();
        $$('.page-content').attr('style', 'margin-top:-44px')
    }

    //获取页面参数
    var userID = ISS.utils.getParameter("userID");
    if (userID && userID != undefined && userID != null && userID != "") {
        iss_localStorage.set("yuqing_appUserId", userID);
        mainView.hideNavbar();
        $$('.page-content').css('style', 'margin-top:-44px')
    }

    // 过滤
    $$(".navbar-inner .right img").hide();

    var Account = ISS.utils.getParameter("Account");
    //获取页面参数
    var scode = ISS.utils.getParameter("scde");
    if (page != undefined) {
        scode = page.query.scde;
    }
    var conditionParams = {
        type: 1,
        serviceName: ISS_Constants.PortalServiceName.GetContentDetails,
        content: JSON.stringify({ 
            format: "json",
            ContentCode: scode,
        }),
    };
    $$.ajax({
        url: ISS_Constants.Url.const_portal_url, //ISS_Constants.Url.defaulturl + ISS_Constants.serviceName.FESTIVALS,
        data: conditionParams,
        crossDomain: true,
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (data, status) {
           data = JSON.parse(data);
            if (data && data.status == "0") {
                data.results[0].BeginDate = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.results[0].BeginDate)));
                data.results[0].EndDate = ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.results[0].EndDate)));
                data.results[0].Address = data.results[0].Address || (data.results[0].Address == null ? "" : data.results[0].Address);
                data.results[0].Telephone = data.results[0].Telephone || (data.results[0].Telephone == null ? "" : data.results[0].Telephone);
                data.results[0].Account = ISS.utils.getParameter("Account");
                data.results[0].RegistEndDate = data.results[0].isNeedRegist ? ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.results[0].RegistEndDate))) :
                                                                             ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.results[0].EndDate)));
                data.results[0].RegistBeginDate = data.results[0].isNeedRegist ? ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.results[0].RegistBeginDate))) :
                                                                             ISS.utils.dateToStr("yyyy-MM-dd", new Date(ISS.utils.ReplaceHMS(data.results[0].BeginDate)));
                //图片split循环
                var pictures = data.results[0].SmallImage.endWith(",") ?
                data.results[0].SmallImage.substring(0, data.results[0].SmallImage.length - 1).split(",") :
                data.results[0].SmallImage.split(",");

                var PicObjs = [];
                for (var i = 0; i < pictures.length; i++) {
                    PicObjs[i] = new Object;
                    PicObjs[i].Pics = pictures[i];
                }

                data.results[0].NewPic = PicObjs;

                var searchTemplate = $$('#template-generalactivity-detail').html();
                var compiledSearchTemplate = Template7.compile(searchTemplate);
                var html = compiledSearchTemplate(data.results[0]);
                $$(".resturant1").html(html);
                $$('#generalactivity_detail_page #calendar-date-format-line-detail').val(data.results[0].BeginDate);
                if (data.results.length <= 0) {
                    $$('#preOrder').attr('style', 'display:none')
                }

                if (new Date() >= new Date(data.results[0].BeginDate) && new Date() < new Date(data.results[0].EndDate)) {
                    //是否需要报名
                    if (!data.results[0].isNeedRegist) {
                        $$('#preOrder').html('无需报名')
                        $$('#preOrder').attr('href', '#')

                    } else {
                        //活动是否开始               
                        if (!new Date() > new Date(data.results[0].RegistBeginDate)) {
                            $$('#preOrder').html('报名未开始')
                            $$('#preOrder').attr('href', '#')
                            $$('#preOrder').on("click","a", function (e) {
				            $$('#preOrder').attr('data-href','') 	
                                    myApp.alert('活动未开始')
                                });	
                        } else if (new Date() >= new Date(data.results[0].RegistEndDate)) {
                            $$('#preOrder').html('报名已结束')
                            $$('#preOrder').attr('href', '#')
                            $$('#preOrder').attr('data-href','') 
                            $$('#preOrder').on("click","a", function (e) {
				                $$('#preOrder').attr('data-href','') 	
                                        myApp.alert('报名已结束')
                                    });
                        }
                        //如果设置上限并且 参与人数大于上限人数
                        else if (data.results[0].isLimitNum && data.results[0].SignCount >= data.results[0].TopNum) {
                            $$('#preOrder').html('报名已满')
                            $$('#preOrder').attr('href', '#')
                        } else {
                            $$('#preOrder').on("click", function (e) {
                                    //取消原有跳转事件
                                    e.stopPropagation();
                                    //保存当前控件
                                    var mythis = $$(this);
                                    //跳转判断
                                    CheckPopLogin(function () {
                                        if ($$('#preOrder').html() == "报名") {
                                            window.location.href = mythis.attr("data-href");
                                        }
                                    });
                                });
                        }
                            
                    }
                } else if (new Date() < new Date(data.results[0].BeginDate)) {
                    $$('#preOrder').html('活动未开始')
                    $$('#preOrder').attr('href', '#')
                } else {
                    $$('#preOrder').html('活动已结束')
                    $$('#preOrder').attr('href', '#')
                    $$('#tel').hide();
                }
                //加载参加人员信息表
                getActivePepole(scode, userID);
            }
        },
        error: function (xhr, status) {
            console.log("ajax error!");
        }
    });
    // 返回
    $$("#generalactivity_detail_page").on("click", "a[data-action='back']", function () {
        var href = $$(this).attr("data-href");
        if (href && href != "") {
            window.location.href = href;
        }
    });
});

var contactsCallback_generalActivityRegister = myApp.onPageInit('generalActivityRegister', function (page) {
    //非微信浏览器下  不显示标题
    if (!ISS.utils.isWeiXin()) {
        mainView.hideNavbar();
        $$('.page-content').attr('style', 'margin-top:-44px')
    }

    //获取页面参数
    var userID = ISS.utils.getParameter("userID");
    var contentid = ISS.utils.getParameter("contentID");
    var code = ISS.utils.getParameter("scde");



    if (userID && userID != undefined && userID != null && userID != "") {
        iss_localStorage.set("yuqing_appUserId", userID);
        mainView.hideNavbar();
    }

    // 返回
    $$("#generalactivity_register_page .link").on("click", function () {
        var href = $$(this).attr("data-href") + "?scde=" + code;
        $$(this).attr("data-href", href)
        if (href && href != "") {
            window.location.href = href;
        }
    });

    $$('#btnsub').on('click', function () {
        var err = "";
        $$('input[id^=txt]').each(function (i, v) {
            if ($$(v).val() == "") {

                err = "请填写完整资料"
                return false
            }
            if ($$(v).attr('style') != "" && $$(v).attr('style') != null) {
                err = "请填写正确资料"
                return false
            }
        })
        if (err != "") {
            myApp.alert(err)
            return false;
        }
        var storedData = myApp.formGetData('activityregister-form');
        storedData.ContentID = contentid;
        storedData.UserID = iss_localStorage.get("yuqing_appUserId");
        storedData.Sex = storedData.Sex == "男" ? 1 : 0;
        storedData.format = "json";
        storedData.Result = "";
        if (storedData) {
            var conditionParams = {
                type: 1,
                serviceName: ISS_Constants.PortalServiceName.GetUserJoinActivity,
                content: JSON.stringify(storedData),
            };
            $$.ajax({
                url: ISS_Constants.Url.const_portal_url,
                data: conditionParams,
                crossDomain: true,
                dataType: 'jsonp',
                jsonp: 'callback',
                success: function (data, status) {

                    data = JSON.parse(data);
                    if (data && data.status == "0") {
                        if (data.results) {
                            myApp.alert('报名成功!', '', function () {
                                window.location.href = "generalActivityDetail.html?scde=" + code;
                            });
                        } else {
                            myApp.alert('请勿重复报名!', '', function () {
                                window.location.href = "generalActivityDetail.html?scde=" + code;
                            });
                        }
                    } else {
                        myApp.alert(data.message);
                    }
                },
                error: function (xhr, status) {
                    console.log(xhr);
                }
            });
        }
        else {
            //alert('There is no stored data for this form yet. Try to change any field')
        }


    });


});

//获取参加活动人物信息
function getActivePepole(code, userID) {
    var conditionParams = {
        type: 1,
        serviceName: ISS_Constants.PortalServiceName.GetActivityUserInfoList,
        content: JSON.stringify({ 
            format: "json",
            ContentCode: code,
        }),
    };
    $$.ajax({
        url: ISS_Constants.Url.const_portal_url,
        data: conditionParams,
        crossDomain: true,
        dataType: 'jsonp',
        jsonp: 'callback',
        success: function (data, status) {

            data = JSON.parse(data);
            if (data && data.status == "0") {
                var searchTemplate = $$('#template-generalactivity-people').html();
                if (searchTemplate) {
                    var compiledTemplate = Template7.compile(searchTemplate);
                    var html = compiledTemplate(data);
                    $$("#generalactivity_detail_page .resturant2").html(html);
                    flag_InfiniteScroll = flag_needScroll = true;
                }

                if (data.results.length <= 0) {
                    $$('.resturant2').attr('style', 'display:none');
                } else {
                    for (var i = 0; i < data.results.length; i++) {
                        var user = data.results[i].UserID;
                        if (iss_localStorage.get("yuqing_appUserId") == user || userID == user) {
                            $$('#preOrder').html('已报名')
                            $$('#preOrder').attr('href', '#')
                        }
                    }
                    $$('.swiper-slide-active').attr('style', 'width: 80px;margin-left: 10px;')
                    $$('.swiper-slide-active').attr('style', 'width: 80px;margin-left: 10px;')
                    $$('.swiper-slide').attr('style', 'width: 80px;margin-left: 10px;')

                    $$('.swiper-slide-img').attr('style', 'width: 48px;height: 48px;background-color: #eee;box-sizing: border-box;border:0');
                    //$$('.swiper-slide p').attr('style', ' margin-left: 14px;');
                    var swiper = new Swiper('.swiper-container', {
                        pagination: '.swiper-pagination',
                        slidesPerView: 3,
                        paginationClickable: true,
                        spaceBetween: 10
                    });
                }

            }
            else {
                $$('.page-content-resturant2').attr('style', 'display:none');
                flag_InfiniteScroll = flag_needScroll = true;
            }
        },
        error: function (xhr, status) {
            console.log("ajax error!");
        }
    });
}

/* 初始化  */
function initData() {
    var href = window.location.href;
    if (href.indexOf(activity) > -1) {
        contactsCallback_generalactivity.trigger();
    }
    else if (href.indexOf(activityDetail) > -1) {
        contactsCallback_generalactivityDetail.trigger();
    } else if (href.indexOf(generalActivityRegister) > -1) {
        contactsCallback_generalActivityRegister.trigger();
    }
}

initData();
